home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d13 / patch12.arc / PATCH.C < prev    next >
Encoding:
C/C++ Source or Header  |  1990-10-02  |  22.8 KB  |  927 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.1.8 90/07/15 14:00:00 aas $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.1.7  90/07/15  14:00:00  aas
  13.  * made init temp file names a little more MS-DOS aware
  14.  *
  15.  * Revision 2.0.1.7  90/05/30  11:30:00  mward
  16.  * Added usage message vars and routines: use_msg, progname, usage, fname
  17.  * Check environment for TMP and init temp file names
  18.  * 
  19.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  20.  * patch12: rindex() wasn't declared
  21.  * 
  22.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  23.  * patch10: exit code improved.
  24.  * patch10: better support for non-flexfilenames.
  25.  * 
  26.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  27.  * Short replacement caused spurious "Out of sync" message.
  28.  * 
  29.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  30.  * Improved diagnostic on sync error.
  31.  * Moved do_ed_script() to pch.c.
  32.  * 
  33.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  34.  * Fuzz factor caused offset of installed lines.
  35.  * 
  36.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  37.  * Backwards search could terminate prematurely.
  38.  * 
  39.  * Revision 2.0  86/09/17  15:37:32  lwall
  40.  * Baseline for netwide release.
  41.  * 
  42.  * Revision 1.5  86/08/01  20:53:24  lwall
  43.  * Changed some %d's to %ld's.
  44.  * Linted.
  45.  * 
  46.  * Revision 1.4  86/08/01  19:17:29  lwall
  47.  * Fixes for machines that can't vararg.
  48.  * Added fuzz factor.
  49.  * Generalized -p.
  50.  * General cleanup.
  51.  * 
  52.  * 85/08/15 van%ucbmonet@berkeley
  53.  * Changes for 4.3bsd diff -c.
  54.  *
  55.  * Revision 1.3  85/03/26  15:07:43  lwall
  56.  * Frozen.
  57.  * 
  58.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  59.  * Changed pfp->_file to fileno(pfp).
  60.  * 
  61.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  62.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  63.  * Also allow ed output to be suppressed.
  64.  * 
  65.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  66.  * Added -p option from jromine@uci-750a.
  67.  * 
  68.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  69.  * Now checks for normalness of file to patch.
  70.  * 
  71.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  72.  * Added -D (#ifdef) option from joe@fluke.
  73.  * 
  74.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  75.  * Made smarter about SCCS subdirectories.
  76.  * 
  77.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  78.  * Added -l switch to do loose string comparison.
  79.  * 
  80.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  81.  * Failed hunk count not reset on multiple patch file.
  82.  * 
  83.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  84.  * Branch for sdcrdcf changes.
  85.  * 
  86.  * Revision 1.2  84/11/29  13:29:51  lwall
  87.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  88.  * multiple calls to mktemp().  Will now work on machines that can only
  89.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  90.  * Various cosmetic changes.
  91.  * 
  92.  * Revision 1.1  84/11/09  17:03:58  lwall
  93.  * Initial revision
  94.  * 
  95.  */
  96.  
  97. #include "INTERN.h"
  98. #include "common.h"
  99. #include "EXTERN.h"
  100. #include "version.h"
  101. #include "util.h"
  102. #include "pch.h"
  103. #include "inp.h"
  104.  
  105. /* procedures */
  106.  
  107. char *fname();
  108. void usage();
  109. void reinitialize_almost_everything();
  110. void get_some_switches();
  111. LINENUM locate_hunk();
  112. void abort_hunk();
  113. void apply_hunk();
  114. void init_output();
  115. void init_reject();
  116. void copy_till();
  117. void spew_output();
  118. void dump_line();
  119. bool patch_match();
  120. bool similar();
  121. void re_input();
  122. void my_exit();
  123.  
  124.  
  125. char *progname;
  126.  
  127. char *use_msg[] = {
  128.     "purpose: apply diff file(s) to original(s) to generate updated file(s)\n",
  129.     "usage:   %s [options] orig patchfile [+ [options] orig]\n",
  130.     "         %s <patchfile\n"
  131.     "options:\n",
  132.     "   -         read patchfile from standard input\n",
  133.     "   -?        display help message (this text)\n",
  134.     "   -b arg    use arg as backup file extension (default is ~ or .orig)\n",
  135.     "   -B arg    use arg as backup file prefix (cancels -b option)\n",
  136.     "   -c        interpret patchfile as context diffs\n",
  137.     "   -d arg    use arg as directory to cd to before continuing\n",
  138.     "   -D arg    surround patched with \"#ifdef arg ... #endif\"\n",
  139.     "   -e        interpret patchfile as an ed script\n",
  140.     "   -f        do not ask questions\n",
  141.     "   -F<num>   set max fuzz factor to <num> (default 2, context diffs only)\n",
  142.     "   -h        display help message (this text)\n",
  143.     "   -l        loose (non \\n whitespace) pattern matching\n",
  144.     "   -n        interpret patchfile as a normal diff\n",
  145.     "   -N        ignore patches that are reversed or already applied\n",
  146.     "   -o arg    use arg as output file name\n",
  147.     "   -p<num>   set path strip count to <num> (default 937,# /'s to strip)\n",
  148.     "   -r arg    use arg as the reject file name\n",
  149.     "   -R        interpret patch as if orig and new were reversed at diff gen\n",
  150.     "   -s        silent operation - no messages\n",
  151.     "   -S        skip current patch, but continue\n",
  152.     "   -v        version - print revision header and patch level\n",
  153.     "   -x<num>   set internal debugging flags to <num>\n",
  154.     "examples\n",
  155.     "   %s <ms_sh_16.dif         # normally read all patches from stdin\n",
  156.     "   %s -S + -S + <patch.dif  # skip 1st and 3rd patches in patch.dif\n",
  157.     "notes:\n"
  158.     "   By default, the patched version is put in place of the original\n",
  159.     NULL
  160. };
  161.  
  162.  
  163. /* Return pointer to first char of file name in spec */
  164.  
  165. char *
  166. fname(char *spec)
  167. {
  168.     char *cptr;
  169.     char *tptr;
  170.  
  171.     cptr = spec + strlen(spec);
  172.     while ((cptr!=spec) && (index("/\\:",*(cptr-1))==Nullch)) {
  173.         cptr--;
  174.     }
  175.     if ((tptr=index(cptr,'.'))!=Nullch) *tptr='\0';
  176.     return (cptr);
  177. }
  178.  
  179.  
  180. /* Print the usage message */
  181.  
  182. void
  183. usage()
  184. {
  185.     char **ptr;
  186.     char *name;
  187.  
  188.     name = fname(progname);
  189.     for (ptr=use_msg; *ptr; ptr++) {
  190.         say2(*ptr,name);
  191.     }
  192. }
  193.  
  194.  
  195. /* Apply a set of diffs as appropriate. */
  196.  
  197. main(argc,argv)
  198. int argc;
  199. char **argv;
  200. {
  201.     LINENUM where;
  202.     LINENUM newwhere;
  203.     LINENUM fuzz;
  204.     LINENUM mymaxfuzz;
  205.     int hunk = 0;
  206.     int failed = 0;
  207.     int failtotal = 0;
  208.     int i;
  209.     char tmpdir[MAXPATH];
  210.     char *tmpenv;
  211.     char c;
  212.  
  213.     progname = (*argv[0]?argv[0]:"patch");
  214.     setbuf(stderr, serrbuf);
  215.     for (i = 0; i<MAXFILEC; i++)
  216.     filearg[i] = Nullch;
  217.  
  218.     /* initialize temp file names */
  219.     tmpenv = getenv("TMP");
  220.     strcpy(tmpdir,(tmpenv!=NULL?tmpenv:""));
  221.     if (strlen(tmpdir))
  222.     if((c=tmpdir[strlen(tmpdir)-1])!='/' && c!='\\')
  223.         strcat(tmpdir,"/");
  224.     TMPOUTNAME = strcat(strcpy(malloc(MAXPATH),tmpdir),fname(TMPOUTNAME));
  225.     TMPINNAME  = strcat(strcpy(malloc(MAXPATH),tmpdir),fname(TMPINNAME));
  226.     TMPREJNAME = strcat(strcpy(malloc(MAXPATH),tmpdir),fname(TMPREJNAME));
  227.     TMPPATNAME = strcat(strcpy(malloc(MAXPATH),tmpdir),fname(TMPPATNAME));
  228.     Mktemp(TMPOUTNAME);
  229.     Mktemp(TMPINNAME);
  230.     Mktemp(TMPREJNAME);
  231.     Mktemp(TMPPATNAME);
  232.  
  233.     /* parse switches */
  234.     Argc = argc;
  235.     Argv = argv;
  236.     get_some_switches();
  237.     
  238.     /* make sure we clean up /tmp in case of disaster */
  239.     set_signals(0);
  240.  
  241.     for (
  242.     open_patch_file(filearg[1]);
  243.     there_is_another_patch();
  244.     reinitialize_almost_everything()
  245.     ) {                    /* for each patch in patch file */
  246.  
  247.     if (outname == Nullch)
  248.         outname = savestr(filearg[0]);
  249.     
  250.     /* initialize the patched file */
  251.     if (!skip_rest_of_patch)
  252.         init_output(TMPOUTNAME);
  253.     
  254.     /* for ed script just up and do it and exit */
  255.     if (diff_type == ED_DIFF) {
  256.         do_ed_script();
  257.         continue;
  258.     }
  259.     
  260.     /* initialize reject file */
  261.     init_reject(TMPREJNAME);
  262.     
  263.     /* find out where all the lines are */
  264.     if (!skip_rest_of_patch)
  265.         scan_input(filearg[0]);
  266.     
  267.     /* from here on, open no standard i/o files, because malloc */
  268.     /* might misfire and we can't catch it easily */
  269.     
  270.     /* apply each hunk of patch */
  271.     hunk = 0;
  272.     failed = 0;
  273.     out_of_mem = FALSE;
  274.     while (another_hunk()) {
  275.         hunk++;
  276.         fuzz = Nulline;
  277.         mymaxfuzz = pch_context();
  278.         if (maxfuzz < mymaxfuzz)
  279.         mymaxfuzz = maxfuzz;
  280.         if (!skip_rest_of_patch) {
  281.         do {
  282.             where = locate_hunk(fuzz);
  283.             if (hunk == 1 && where == Nulline && !force) {
  284.                         /* dwim for reversed patch? */
  285.             if (!pch_swap()) {
  286.                 if (fuzz == Nulline)
  287.                 say1(
  288. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  289.                 continue;
  290.             }
  291.             reverse = !reverse;
  292.             where = locate_hunk(fuzz);  /* try again */
  293.             if (where == Nulline) {        /* didn't find it swapped */
  294.                 if (!pch_swap())         /* put it back to normal */
  295.                 fatal1("Lost hunk on alloc error!\n");
  296.                 reverse = !reverse;
  297.             }
  298.             else if (noreverse) {
  299.                 if (!pch_swap())         /* put it back to normal */
  300.                 fatal1("Lost hunk on alloc error!\n");
  301.                 reverse = !reverse;
  302.                 say1(
  303. "Ignoring previously applied (or reversed) patch.\n");
  304.                 skip_rest_of_patch = TRUE;
  305.             }
  306.             else {
  307.                 ask3(
  308. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  309.                 reverse ? "R" : "Unr",
  310.                 reverse ? "Assume" : "Ignore");
  311.                 if (*buf == 'n') {
  312.                 ask1("Apply anyway? [n] ");
  313.                 if (*buf != 'y')
  314.                     skip_rest_of_patch = TRUE;
  315.                 where = Nulline;
  316.                 reverse = !reverse;
  317.                 if (!pch_swap())  /* put it back to normal */
  318.                     fatal1("Lost hunk on alloc error!\n");
  319.                 }
  320.             }
  321.             }
  322.         } while (!skip_rest_of_patch && where == Nulline &&
  323.             ++fuzz <= mymaxfuzz);
  324.  
  325.         if (skip_rest_of_patch) {        /* just got decided */
  326.             Fclose(ofp);
  327.             ofp = Nullfp;
  328.         }
  329.         }
  330.  
  331.         newwhere = pch_newfirst() + last_offset;
  332.         if (skip_rest_of_patch) {
  333.         abort_hunk();
  334.         failed++;
  335.         if (verbose)
  336.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  337.         }
  338.         else if (where == Nulline) {
  339.         abort_hunk();
  340.         failed++;
  341.         if (verbose)
  342.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  343.         }
  344.         else {
  345.         apply_hunk(where);
  346.         if (verbose) {
  347.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  348.             if (fuzz)
  349.             say2(" with fuzz %ld", fuzz);
  350.             if (last_offset)
  351.             say3(" (offset %ld line%s)",
  352.                 last_offset, last_offset==1L?"":"s");
  353.             say1(".\n");
  354.         }
  355.         }
  356.     }
  357.  
  358.     if (out_of_mem && using_plan_a) {
  359.         Argc = Argc_last;
  360.         Argv = Argv_last;
  361.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  362.         continue;
  363.     }
  364.     
  365.     assert(hunk);
  366.     
  367.     /* finish spewing out the new file */
  368.     if (!skip_rest_of_patch)
  369.         spew_output();
  370.     
  371.     /* and put the output where desired */
  372.     ignore_signals();
  373.     if (!skip_rest_of_patch) {
  374.         if (move_file(TMPOUTNAME, outname) < 0) {
  375.         toutkeep = TRUE;
  376.         chmod(TMPOUTNAME, filemode);
  377.         }
  378.         else
  379.         chmod(outname, filemode);
  380.     }
  381.     Fclose(rejfp);
  382.     rejfp = Nullfp;
  383.     if (failed) {
  384.         failtotal += failed;
  385.         if (!*rejname) {
  386.         Strcpy(rejname, outname);
  387. #ifndef FLEXFILENAMES
  388.         {
  389.             char *rindex();
  390.             char *s = rindex(rejname,'/');
  391.  
  392.             if (!s)
  393.             s = rejname;
  394.             if (strlen(s) > 13)
  395.             if (s[12] == '.')    /* try to preserve difference */
  396.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  397.             s[13] = '\0';
  398.         }
  399. #endif
  400.         Strcat(rejname, REJEXT);
  401.         }
  402.         if (skip_rest_of_patch) {
  403.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  404.             failed, hunk, rejname);
  405.         }
  406.         else {
  407.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  408.             failed, hunk, rejname);
  409.         }
  410.         if (move_file(TMPREJNAME, rejname) < 0)
  411.         trejkeep = TRUE;
  412.     }
  413.     set_signals(1);
  414.     }
  415.     my_exit(failtotal);
  416. }
  417.  
  418. /* Prepare to find the next patch to do in the patch file. */
  419.  
  420. void
  421. reinitialize_almost_everything()
  422. {
  423.     re_patch();
  424.     re_input();
  425.  
  426.     input_lines = 0;
  427.     last_frozen_line = 0;
  428.  
  429.     filec = 0;
  430.     if (filearg[0] != Nullch && !out_of_mem) {
  431.     free(filearg[0]);
  432.     filearg[0] = Nullch;
  433.     }
  434.  
  435.     if (outname != Nullch) {
  436.     free(outname);
  437.     outname = Nullch;
  438.     }
  439.  
  440.     last_offset = 0;
  441.  
  442.     diff_type = 0;
  443.  
  444.     if (revision != Nullch) {
  445.     free(revision);
  446.     revision = Nullch;
  447.     }
  448.  
  449.     reverse = FALSE;
  450.     skip_rest_of_patch = FALSE;
  451.  
  452.     get_some_switches();
  453.  
  454.     if (filec >= 2)
  455.     fatal1("You may not change to a different patch file.\n");
  456. }
  457.  
  458. /* Process switches and filenames up to next '+' or end of list. */
  459.  
  460. void
  461. get_some_switches()
  462. {
  463.     Reg1 char *s;
  464.  
  465.     rejname[0] = '\0';
  466.     Argc_last = Argc;
  467.     Argv_last = Argv;
  468.     if (!Argc)
  469.     return;
  470.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  471.     s = Argv[0];
  472.     if (strEQ(s, "+")) {
  473.         return;            /* + will be skipped by for loop */
  474.     }
  475.     if (*s != '-' || !s[1]) {
  476.         if (filec == MAXFILEC)
  477.         fatal1("Too many file arguments.\n");
  478.         filearg[filec++] = savestr(s);
  479.     }
  480.     else {
  481.         switch (*++s) {
  482.         case 'b':
  483.         origext = savestr(Argv[1]);
  484.         Argc--,Argv++;
  485.         break;
  486.         case 'B':
  487.         origprae = savestr(Argv[1]);
  488.         Argc--,Argv++;
  489.         break;
  490.         case 'c':
  491.         diff_type = CONTEXT_DIFF;
  492.         break;
  493.         case 'd':
  494.         if (!*++s) {
  495.             Argc--,Argv++;
  496.             s = Argv[0];
  497.         }
  498.         if (chdir(s) < 0)
  499.             fatal2("Can't cd to %s.\n", s);
  500.         break;
  501.         case 'D':
  502.             do_defines = TRUE;
  503.         if (!*++s) {
  504.             Argc--,Argv++;
  505.             s = Argv[0];
  506.         }
  507.         if (!isalpha(*s))
  508.             fatal1("Argument to -D not an identifier.\n");
  509.         Sprintf(if_defined, "#ifdef %s\n", s);
  510.         Sprintf(not_defined, "#ifndef %s\n", s);
  511.         Sprintf(end_defined, "#endif /* %s */\n", s);
  512.         break;
  513.         case 'e':
  514.         diff_type = ED_DIFF;
  515.         break;
  516.         case 'f':
  517.         force = TRUE;
  518.         break;
  519.         case 'F':
  520.         if (*++s == '=')
  521.             s++;
  522.         maxfuzz = atoi(s);
  523.         break;
  524.         case '?':
  525.         case 'h':
  526.         usage();
  527.         my_exit(0);
  528.         break;
  529.         case 'l':
  530.         canonicalize = TRUE;
  531.         break;
  532.         case 'n':
  533.         diff_type = NORMAL_DIFF;
  534.         break;
  535.         case 'N':
  536.         noreverse = TRUE;
  537.         break;
  538.         case 'o':
  539.         outname = savestr(Argv[1]);
  540.         Argc--,Argv++;
  541.         break;
  542.         case 'p':
  543.         if (*++s == '=')
  544.             s++;
  545.         strippath = atoi(s);
  546.         break;
  547.         case 'r':
  548.         Strcpy(rejname, Argv[1]);
  549.         Argc--,Argv++;
  550.         break;
  551.         case 'R':
  552.         reverse = TRUE;
  553.         break;
  554.         case 's':
  555.         verbose = FALSE;
  556.         break;
  557.         case 'S':
  558.         skip_rest_of_patch = TRUE;
  559.         break;
  560.         case 'v':
  561.         version();
  562.         break;
  563. #ifdef DEBUGGING
  564.         case 'x':
  565.         debug = atoi(s+1);
  566.         break;
  567. #endif
  568.         default:
  569.         say2("Unrecognized switch: %s\n", Argv[0]);
  570.         usage();
  571.         my_exit(1);
  572.         }
  573.     }
  574.     }
  575. }
  576.  
  577. /* Attempt to find the right place to apply this hunk of patch. */
  578.  
  579. LINENUM
  580. locate_hunk(fuzz)
  581. LINENUM fuzz;
  582. {
  583.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  584.     Reg2 LINENUM offset;
  585.     LINENUM pat_lines = pch_ptrn_lines();
  586.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  587.                 - pat_lines + 1; 
  588.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  589.                 + pch_context();
  590.  
  591.     if (!pat_lines)            /* null range matches always */
  592.     return first_guess;
  593.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  594.     max_neg_offset = first_guess - 1;
  595.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  596.     return first_guess;
  597.     for (offset = 1; ; offset++) {
  598.     Reg5 bool check_after = (offset <= max_pos_offset);
  599.     Reg6 bool check_before = (offset <= max_neg_offset);
  600.  
  601.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  602. #ifdef DEBUGGING
  603.         if (debug & 1)
  604.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  605. #endif
  606.         last_offset = offset;
  607.         return first_guess+offset;
  608.     }
  609.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  610. #ifdef DEBUGGING
  611.         if (debug & 1)
  612.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  613. #endif
  614.         last_offset = -offset;
  615.         return first_guess-offset;
  616.     }
  617.     else if (!check_before && !check_after)
  618.         return Nulline;
  619.     }
  620. }
  621.  
  622. /* We did not find the pattern, dump out the hunk so they can handle it. */
  623.  
  624. void
  625. abort_hunk()
  626. {
  627.     Reg1 LINENUM i;
  628.     Reg2 LINENUM pat_end = pch_end();
  629.     /* add in last_offset to guess the same as the previous successful hunk */
  630.     LINENUM oldfirst = pch_first() + last_offset;
  631.     LINENUM newfirst = pch_newfirst() + last_offset;
  632.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  633.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  634.     char *stars = (diff_type == NEW_CONTEXT_DIFF ? " ****" : "");
  635.     char *minuses = (diff_type == NEW_CONTEXT_DIFF ? " ----" : " -----");
  636.  
  637.     fprintf(rejfp, "***************\n");
  638.     for (i=0; i<=pat_end; i++) {
  639.     switch (pch_char(i)) {
  640.     case '*':
  641.         if (oldlast < oldfirst)
  642.         fprintf(rejfp, "*** 0%s\n", stars);
  643.         else if (oldlast == oldfirst)
  644.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  645.         else
  646.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  647.         break;
  648.     case '=':
  649.         if (newlast < newfirst)
  650.         fprintf(rejfp, "--- 0%s\n", minuses);
  651.         else if (newlast == newfirst)
  652.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  653.         else
  654.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  655.         break;
  656.     case '\n':
  657.         fprintf(rejfp, "%s", pfetch(i));
  658.         break;
  659.     case ' ': case '-': case '+': case '!':
  660.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  661.         break;
  662.     default:
  663.         say1("Fatal internal error in abort_hunk().\n"); 
  664.         abort();
  665.     }
  666.     }
  667. }
  668.  
  669. /* We found where to apply it (we hope), so do it. */
  670.  
  671. void
  672. apply_hunk(where)
  673. LINENUM where;
  674. {
  675.     Reg1 LINENUM old = 1;
  676.     Reg2 LINENUM lastline = pch_ptrn_lines();
  677.     Reg3 LINENUM new = lastline+1;
  678. #define OUTSIDE 0
  679. #define IN_IFNDEF 1
  680. #define IN_IFDEF 2
  681. #define IN_ELSE 3
  682.     Reg4 int def_state = OUTSIDE;
  683.     Reg5 bool R_do_defines = do_defines;
  684.     Reg6 LINENUM pat_end = pch_end();
  685.  
  686.     where--;
  687.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  688.     new++;
  689.     
  690.     while (old <= lastline) {
  691.     if (pch_char(old) == '-') {
  692.         copy_till(where + old - 1);
  693.         if (R_do_defines) {
  694.         if (def_state == OUTSIDE) {
  695.             fputs(not_defined, ofp);
  696.             def_state = IN_IFNDEF;
  697.         }
  698.         else if (def_state == IN_IFDEF) {
  699.             fputs(else_defined, ofp);
  700.             def_state = IN_ELSE;
  701.         }
  702.         fputs(pfetch(old), ofp);
  703.         }
  704.         last_frozen_line++;
  705.         old++;
  706.     }
  707.     else if (new > pat_end)
  708.         break;
  709.     else if (pch_char(new) == '+') {
  710.         copy_till(where + old - 1);
  711.         if (R_do_defines) {
  712.         if (def_state == IN_IFNDEF) {
  713.             fputs(else_defined, ofp);
  714.             def_state = IN_ELSE;
  715.         }
  716.         else if (def_state == OUTSIDE) {
  717.             fputs(if_defined, ofp);
  718.             def_state = IN_IFDEF;
  719.         }
  720.         }
  721.         fputs(pfetch(new), ofp);
  722.         new++;
  723.     }
  724.     else {
  725.         if (pch_char(new) != pch_char(old)) {
  726.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  727.             pch_hunk_beg() + old,
  728.             pch_hunk_beg() + new);
  729. #ifdef DEBUGGING
  730.         say3("oldchar = '%c', newchar = '%c'\n",
  731.             pch_char(old), pch_char(new));
  732. #endif
  733.         my_exit(1);
  734.         }
  735.         if (pch_char(new) == '!') {
  736.         copy_till(where + old - 1);
  737.         if (R_do_defines) {
  738.            fputs(not_defined, ofp);
  739.            def_state = IN_IFNDEF;
  740.         }
  741.         while (pch_char(old) == '!') {
  742.             if (R_do_defines) {
  743.             fputs(pfetch(old), ofp);
  744.             }
  745.             last_frozen_line++;
  746.             old++;
  747.         }
  748.         if (R_do_defines) {
  749.             fputs(else_defined, ofp);
  750.             def_state = IN_ELSE;
  751.         }
  752.         while (pch_char(new) == '!') {
  753.             fputs(pfetch(new), ofp);
  754.             new++;
  755.         }
  756.         if (R_do_defines) {
  757.             fputs(end_defined, ofp);
  758.             def_state = OUTSIDE;
  759.         }
  760.         }
  761.         else {
  762.         assert(pch_char(new) == ' ');
  763.         old++;
  764.         new++;
  765.         }
  766.     }
  767.     }
  768.     if (new <= pat_end && pch_char(new) == '+') {
  769.     copy_till(where + old - 1);
  770.     if (R_do_defines) {
  771.         if (def_state == OUTSIDE) {
  772.             fputs(if_defined, ofp);
  773.         def_state = IN_IFDEF;
  774.         }
  775.         else if (def_state == IN_IFNDEF) {
  776.         fputs(else_defined, ofp);
  777.         def_state = IN_ELSE;
  778.         }
  779.     }
  780.     while (new <= pat_end && pch_char(new) == '+') {
  781.         fputs(pfetch(new), ofp);
  782.         new++;
  783.     }
  784.     }
  785.     if (R_do_defines && def_state != OUTSIDE) {
  786.     fputs(end_defined, ofp);
  787.     }
  788. }
  789.  
  790. /* Open the new file. */
  791.  
  792. void
  793. init_output(name)
  794. char *name;
  795. {
  796.     ofp = fopen(name, "w");
  797.     if (ofp == Nullfp)
  798.     fatal2("patch: can't create %s.\n", name);
  799. }
  800.  
  801. /* Open a file to put hunks we can't locate. */
  802.  
  803. void
  804. init_reject(name)
  805. char *name;
  806. {
  807.     rejfp = fopen(name, "w");
  808.     if (rejfp == Nullfp)
  809.     fatal2("patch: can't create %s.\n", name);
  810. }
  811.  
  812. /* Copy input file to output, up to wherever hunk is to be applied. */
  813.  
  814. void
  815. copy_till(lastline)
  816. Reg1 LINENUM lastline;
  817. {
  818.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  819.  
  820.     if (R_last_frozen_line > lastline)
  821.     say1("patch: misordered hunks! output will be garbled.\n");
  822.     while (R_last_frozen_line < lastline) {
  823.     dump_line(++R_last_frozen_line);
  824.     }
  825.     last_frozen_line = R_last_frozen_line;
  826. }
  827.  
  828. /* Finish copying the input file to the output file. */
  829.  
  830. void
  831. spew_output()
  832. {
  833. #ifdef DEBUGGING
  834.     if (debug & 256)
  835.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  836. #endif
  837.     if (input_lines)
  838.     copy_till(input_lines);        /* dump remainder of file */
  839.     Fclose(ofp);
  840.     ofp = Nullfp;
  841. }
  842.  
  843. /* Copy one line from input to output. */
  844.  
  845. void
  846. dump_line(line)
  847. LINENUM line;
  848. {
  849.     Reg1 char *s;
  850.     Reg2 char R_newline = '\n';
  851.  
  852.     /* Note: string is not null terminated. */
  853.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  854. }
  855.  
  856. /* Does the patch pattern match at line base+offset? */
  857.  
  858. bool
  859. patch_match(base, offset, fuzz)
  860. LINENUM base;
  861. LINENUM offset;
  862. LINENUM fuzz;
  863. {
  864.     Reg1 LINENUM pline = 1 + fuzz;
  865.     Reg2 LINENUM iline;
  866.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  867.  
  868.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  869.     if (canonicalize) {
  870.         if (!similar(ifetch(iline, (offset >= 0)),
  871.              pfetch(pline),
  872.              pch_line_len(pline) ))
  873.         return FALSE;
  874.     }
  875.     else if (strnNE(ifetch(iline, (offset >= 0)),
  876.            pfetch(pline),
  877.            pch_line_len(pline) ))
  878.         return FALSE;
  879.     }
  880.     return TRUE;
  881. }
  882.  
  883. /* Do two lines match with canonicalized white space? */
  884.  
  885. bool
  886. similar(a,b,len)
  887. Reg1 char *a;
  888. Reg2 char *b;
  889. Reg3 int len;
  890. {
  891.     while (len) {
  892.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  893.         if (!isspace(*a))        /* no corresponding whitespace? */
  894.         return FALSE;
  895.         while (len && isspace(*b) && *b != '\n')
  896.         b++,len--;        /* skip pattern whitespace */
  897.         while (isspace(*a) && *a != '\n')
  898.         a++;            /* skip target whitespace */
  899.         if (*a == '\n' || *b == '\n')
  900.         return (*a == *b);    /* should end in sync */
  901.     }
  902.     else if (*a++ != *b++)        /* match non-whitespace chars */
  903.         return FALSE;
  904.     else
  905.         len--;            /* probably not necessary */
  906.     }
  907.     return TRUE;            /* actually, this is not reached */
  908.                     /* since there is always a \n */
  909. }
  910.  
  911. /* Exit with cleanup. */
  912.  
  913. void
  914. my_exit(status)
  915. int status;
  916. {
  917.     Unlink(TMPINNAME);
  918.     if (!toutkeep) {
  919.     Unlink(TMPOUTNAME);
  920.     }
  921.     if (!trejkeep) {
  922.     Unlink(TMPREJNAME);
  923.     }
  924.     Unlink(TMPPATNAME);
  925.     exit(status);
  926. }
  927.